<!-- 客户备案页 -->
<template>
	<div>
		<!-- 引入公共头部组件:rightText="rightText" @rightEvent="onClickLeft" -->
		<div style="background-color: #fff;padding:10px 10px 50px 10px">
			<!-- 备案表单内容区域 style="height: 100%; overflow: auto; box-sizing: border-box"-->
			<uni-forms ref="form" :modelValue="entity" label-width="120px" :rules="dynamicRules">
				<uni-forms-item name="cCusCode" label="客户编码:">
					<uni-easyinput v-model="entity.cCusCode" placeholder="请输入客户编码" :disabled="true" />
				</uni-forms-item>
				<uni-forms-item name="cCusName" label="客户名称:" :rules="$rules.handle.cCusName" required>
					<uni-easyinput v-model="entity.cCusName" placeholder="请输入客户名称" />
				</uni-forms-item>
				<uni-forms-item name="cCusAbbName" label="客户简称:">
					<uni-easyinput v-model="entity.cCusAbbName" placeholder="请输入客户简称" />
				</uni-forms-item>
				<uni-forms-item name="ONOfCompany" label="公司正式名称:">
					<uni-easyinput v-model="entity.ONOfCompany" placeholder="请输入公司正式名称" />
				</uni-forms-item>
				<uni-forms-item name="cTrade" label="行业分类:">
					<uni-easyinput v-model="entity.cTrade" placeholder="请输入行业分类" />
				</uni-forms-item>
				<uni-forms-item name="SaleType" label="销售性质:">
					<uni-data-select placeholder="请选择销售性质" v-model="entity.SaleType"
						:localdata="columns"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item name="ParentName" right-icon="edit" label="上级单位:" placeholder="选择上级单位"
					v-model="entity.ParentName">
					<div @click="CustomerChoice">
						<uni-easyinput v-model="entity.ParentName" placeholder="请选择上级单位" suffixIcon="search" />
					</div>
				</uni-forms-item>

				<uni-forms-item name="cCusTypeName" label="客户类型:">
					<uni-data-select placeholder="选请择客户类型" v-model="entity.cCusTypeName"
						:localdata="columnsType"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item name="CustomerOrigin" label="客户来源:">
					<uni-data-select placeholder="选请择客户来源" v-model="entity.CustomerOrigin"
						:localdata="CustomerOriginOptions"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="省:" :rules="$rules.handle.cProvince" required name="cProvince">
					<uni-data-select placeholder="请选择省份" v-model="entity.cProvince" @change="cProvinceNameChange"
						:localdata="columnscProvince"></uni-data-select>
				</uni-forms-item>
				<!--  -->
				<uni-forms-item name="cCity" label="市:" :rules="$rules.handle.cCity" required>
					<uni-data-select placeholder="请选择市" v-model="entity.cCity" :localdata="columnscCity"
						@change="cCityNameChange"></uni-data-select>
				</uni-forms-item>
				<!--   -->
				<uni-forms-item name="cCounty" label="区:" :rules="$rules.handle.cCounty" required>
					<uni-data-select placeholder="请选择区" v-model="entity.cCounty" :localdata="columnscCounty"
						@change="cCountyNameChange"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item name="cCusAccount" label="银行账号:">
					<uni-easyinput v-model="entity.cCusAccount" placeholder="请输入银行账号" />
				</uni-forms-item>
				<uni-forms-item name="cCusBank" label="开户银行:">
					<uni-easyinput v-model="entity.cCusBank" placeholder="请输入开户银行" />
				</uni-forms-item>
				<uni-forms-item name="iARMoney" label="应收余额:">
					<uni-easyinput v-model="entity.iARMoney" placeholder="请输入应收余额" />
				</uni-forms-item>
				<uni-forms-item name="cCusLPerson" label="法人:">
					<uni-easyinput v-model="entity.cCusLPerson" placeholder="请输入法人" />
				</uni-forms-item>
				<uni-forms-item name="cCusRegCode" label="营业执照:">
					<uni-easyinput v-model="entity.cCusRegCode" placeholder="请输入营业执照号码" />
				</uni-forms-item>
				<uni-forms-item name="dLastDate" label="余额初始日期:">
					<view @click="DateChange($event,'dLastDate')">
						<uni-easyinput v-model="entity.dLastDate" placeholder="请选择余额初始日期" :disabled="true"
							:inputBorder="false" />
					</view>
				</uni-forms-item>
				<uni-forms-item name="cCusPhone" label="手机号:">
					<uni-easyinput v-model="entity.cCusPhone" placeholder="请输入手机号" type="number" @input="inputChange" />
				</uni-forms-item>
				<uni-forms-item name="IsInternal" label="内部企业:" :rules="$rules.handle.IsInternal" required>
					<uni-data-select placeholder="请选择内部企业" v-model="entity.IsInternal"
						:localdata="IsInternalOptions"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item name="DeptCode" label="所属公司:" :rules="$rules.handle.DeptCode" required>
					<uni-data-select placeholder="请选择所属公司" v-model="entity.DeptCode"
						:localdata="DeptCodeOptions"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item name="IRInfo" label="开票要求:">
					<uni-easyinput v-model="entity.IRInfo" placeholder="请输入开票要求" type="textarea" />
				</uni-forms-item>
				<uni-forms-item name="cCusAddress" label="地址:">
					<uni-easyinput v-model="entity.cCusAddress" placeholder="请输入地址" type="textarea" />
				</uni-forms-item>
			</uni-forms>
		</div>

		<div>
			<div class="submitButton">
				<u-button type="primary" @click="onSubmit" :loading="loading">提交</u-button>
			</div>
		</div>
		<!-- 选择日期 -->
		<u-calendar v-model="isCalendar" :mode="mode" placeholder="请选择日期" @change="calendarChange"></u-calendar>
		<!-- 客户组件 -->
		<Myuser @customerChoice="Client" ref="myuser" />
	</div>
</template>

<script>
	import {
		mapState
	} from "vuex";
	import {
		GetDataListByPIdListProvince,
		GetDataListByPIdListcCity,
		GetDataListByPIdListcCounty,
		CustomerInfoSaveData,
		Cust_CustomerApplySaveData,
		GetTheDataByDicKey,
		// 客户备案获取所属公司
		Base_u8databaseGetbase_u8databaseDataList
	} from '@/api/interface.js'
	// //客户组件
	import Myuser from "../../components/OwnUser.vue";
	export default {
		components: {
			Myuser,
		},
		data() {
			return {
				// 点击的是哪一个区域的日期组件
				DateType: "",
				isCalendar: false, //是否显示日期
				// 日期选择
				mode: 'date',
				loading: false,
				// 内部企业下拉数据
				IsInternalOptions: [{
						text: '是',
						value: 1
					},
					{
						text: '否',
						value: 0
					}
				],
				// 所属公司下拉列表数据
				DeptCodeOptions: [],
				// 表单校验
				dynamicRules: {
					// 营业执照格式校验
					cCusRegCode: {
						rules: [{
								required: false,
								message: "",
							},
							{
								validateFunction: (rule, value, data, callback) => {
									let cCusRegCodeReg = (
										/^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$/
									); //手机号码
									if (!cCusRegCodeReg.test(value)) {
										callback('营业执照格式不正确，请重新输入')
									}
								}
							}
						],
					},

					// 手机格式校验
					cCusPhone: {
						rules: [{
								required: false,
								message: "",
							},
							{
								validateFunction: (rule, value, data, callback) => {
									let cCusRegCodeReg = (
										/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/
									); //手机号码
									if (!cCusRegCodeReg.test(value)) {
										callback('手机号格式不正确，请重新输入')
									}
								}
							}
						],
					},
				},
				entity: {
					cCusName: "",
					ProvinceName: "",
					CityName: "",
					CountyName: "",
					cCusTypeName: "备客客户"
				},
				data: [],
				show: false,
				Id: "",
				row: {},
				listChildren: [],
				ListProvince: [],
				columnscProvince: [], //省
				columnscCity: [], //市
				columnscCounty: [], //区
				// 客户来源下拉列表数据
				CustomerOriginOptions: [],
				columnsType: [{
						text: "备案",
						value: -1,
					},
					{
						text: "潜在",
						value: 0,
					},
					{
						text: "正式",
						value: 1,
					},
					{
						text: "休眠",
						value: 2,
					},
				],
				columns: [{
					value: 1,
					text: "直销",
				}, {
					value: 2,
					text: "渠道",
				}, {
					value: 3,
					text: "代理"
				}],
				pagination: {
					// 当前页数
					current: 1,
					// 每页条数
					pageSize: 10,
					// 总条数
					Total: 0,
					showTotal: 0,
				},
				// 存储用户信息
				userInfo: {},
				obj: {},
			};
		},
		// watch: {
		//   //监听显示高度
		//   showHeight: function () {
		//     if (this.docmHeight > this.showHeight) {
		//       //隐藏
		//       this.hideshow = false;
		//     } else {
		//       //显示
		//       this.hideshow = true;
		//     }
		//   },
		// },
		onLoad() {
			// 获取缓存用户信息
			this.userInfo = this.UserInfo.UserInfo
			console.log('获取用户信息', this.userInfo)
			// 获取省份信息
			this.getProvinceListData('初始');
			// 客户来源赋值
			this.CustomerOriginOptions = this.CustSourceOptions

			// 获取所属公司
			this.getBase_u8databaseGetbase_u8databaseDataList()
		},
		computed: {
			...mapState(["CustSourceOptions", "UserInfo"]),
		},
		methods: {
			// 只能输入正整数
			inputChange(event) {
				const inputRule = /[^1-9]/g //只能输入正整数
				if (event < 0) {
					this.$nextTick(() => {
						this.$set(this.entity, 'cCusPhone', inputRule);
					});
				}
			},
			// 日期选择
			DateChange(event, key) {
				console.log('日期选择', event, key)
				this.DateType = key
				this.isCalendar = true
			},
			// 选择日期确定
			calendarChange(event) {
				console.log('选择日期确定了----', event)
				this.$set(this.entity, this.DateType, event.result);
			},
			// 选择省份变化事件
			cProvinceNameChange(event) {
				this.entity.cProvinceName = this.ListProvince.filter(item => item.Id === event)[0].Name
				let cProvince = this.ListProvince.filter(item => item.Id === event)[0].Id
				this.entity.cCity = null
				this.$refs.form.setValue('cProvince', cProvince)
				// 获取市信息
				this.getCityListData(this.entity.cProvince)
			},
			// 市级变化回调
			cCityNameChange(event) {
				this.entity.cCityName = this.listChildren.filter(item => item.Id === event)[0].Name
				let cCity = this.listChildren.filter(item => item.Id === event)[0].Id
				this.entity.cCounty = null
				this.$refs.form.setValue('cCity', cCity)
				// 获取区信息
				this.getVillage(this.entity.cCity)
			},
			// 区改变事件
			cCountyNameChange(event) {
				this.entity.cCountyName = this.listcounty.filter(item => item.Id === event)[0].Name
				let cCounty = this.listcounty.filter(item => item.Id === event)[0].Id
				this.$refs.form.setValue('cCounty', cCounty)
			},
			//客户组件选择的本条客户的数据
			Client(a) {
				this.$set(this.entity, "CustomerName", a.cCusName);
				this.$set(this.entity, "ParentName", a.cCusName);
				this.entity.ParentId = a.Id;
				this.$forceUpdate()
			},

			// 客户组件传递过来的方法
			CustomerChoice(e) {
				this.$refs.myuser.openForm();
			},

			// 获取备案客户所属公司
			getBase_u8databaseGetbase_u8databaseDataList() {
				Base_u8databaseGetbase_u8databaseDataList({}).then(resJson => {
					console.log('获取所诉公司-------------', resJson.Data)
					if (resJson.Success) {
						if (resJson.Data) {
							resJson.Data.forEach(item => {
								item.text = item.DeptName
								item.value = item.Id
							})
						}

						this.DeptCodeOptions = resJson.Data
					}
				})
			},



			// 获取客户列表数据
			getDataList() {
				this.selectedRowKeys = [];
				this.http
					.post(
						"/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition", {
							// 当前页数
							PageIndex: this.pagination.current,
							// 每页显示10条
							PageRows: this.pagination.pageSize,
							SortField: "Id",
							SortType: "asc",
							Search: this.queryParam,
						}
					)
					.then((resJson) => {
						if (resJson.Data.length == 0) {
							// 如果没有数据显示备案按钮
							this.rightText = "备案";
						} else {
							this.rightText = "";
						}
						//  计算当前总页数  用于后续对比
						let totalPage = this.pagination.current * 10;
						if (this.pagination.Total == this.pagination.current) {
							this.dataList = resJson.Data;
						} else {
							// 每页条数+5
							this.pagination.current += 1;
							// 赋值加载的总条数 用于和原始总条数做比较
							this.pagination.showTotal = totalPage;
							// 赋值总条数
							this.pagination.Total = resJson.Total;
							let arr = resJson.Data;
							// 拼接数组
							this.data = this.data.concat(arr);
						}
						// 清除加载状态
						this.loading = false;
						if (this.pagination.showTotal <= this.pagination.Total) {
							// 数据没有全部加载完成
							this.loading = false;
						} else {
							// 数据全部加载完成
							this.loading = false;
							// 注意，，必须return  否则接口回频繁请求
							return;
						}
					});
			},

			//获取省份信息
			getProvinceListData(type) {
				GetDataListByPIdListProvince({})
					.then(resJson => {
						this.ListProvince = resJson.Data;
						this.columnscProvince = resJson.Data.map(item => {
							return {
								value: item.Id,
								text: item.Name
							}
						});

					});
			},
			// 获取市信息
			getCityListData(e, type) {
				GetDataListByPIdListcCity({
						Id: e
					})
					.then(resJson => {
						this.listChildren = resJson.Data;
						this.columnscCity = resJson.Data.map((item, index) => {
							return {
								value: item.Id,
								text: item.Name
							}
						});
						this.entity.cCounty = null

					});
			},
			// 获取区信息
			getVillage(e, type) {
				console.log('开始获取区了', e, type, this.entity)
				GetDataListByPIdListcCounty({
						Id: e
					})
					.then(resJson => {
						this.listcounty = resJson.Data;
						this.columnscCounty = resJson.Data.map((item, index) => {
							return {
								value: item.Id,
								text: item.Name
							}
						});
					});
			},



			// 备案提交
			onSubmit(values) {
				var that = this;
				this.entity.cCusType = -1;
				console.log('校验之前', this.entity)

				// 手动校验
				// if (this.entity.cCusName === "") return this.$errorToast('请输入客户名称')
				// if (this.entity.ProvinceName === "") {
				// 	this.$errorToast('请选择省')
				// 	return
				// }
				// if (this.entity.CityName === "") return this.$errorToast('请选择市')
				// if (this.entity.CountyName === "") return this.$errorToast('请选择区')

				this.$refs.form.validate().then(res => {
					this.loading = true
					uni.showLoading({
						title: '备案中'
					})
					let newEntity = JSON.parse(JSON.stringify(this.entity))

					// 单独处理客户类型参数
					if (newEntity.cCusTypeName == -1) {
						newEntity.cCusTypeName = this.columnsType[0].text
					} else if (newEntity.cCusTypeName == 0) {
						newEntity.cCusTypeName = this.columnsType[1].text
					} else if (newEntity.cCusTypeName == 1) {
						newEntity.cCusTypeName = this.columnsType[2].text
					} else {
						newEntity.cCusTypeName = this.columnsType[3].text
					}
					// 单独处理销售性质参数
					let text = this.columns[newEntity.SaleType - 1].text
					newEntity.SaleType = text
					this.loading = true
					console.log('客户备案备案备案备案备案开始提交了----', this.entity)
					CustomerInfoSaveData(this.entity)
						.then((resJson) => {
							this.loading = false;
							if (resJson.Success) {
								// Toast.success("操作成功");
								let obj = {};
								obj.CustomerId = resJson.Data.Id;
								obj.CustomerName = resJson.Data.cCusName;
								obj.Id = null;
								obj.SalesmanId = this.userInfo.Id;
								obj.SalesmanName = this.userInfo.RealName;
								obj.ApprovalStatus = resJson.Data.cCusType;
								obj.ApplyDate = resJson.Data.CreateTime;
								obj.Type = "3";
								console.log(obj);
								this.obj = obj;
								that.AddRecord(obj);
							} else {
								that.loading = false
								this.$errorToast(resJson.Msg)
							}
						});

				}).catch(err => {
					uni.hideLoading()
					that.loading = false
				})


			},

			AddRecord(obj) {
				var that = this
				Cust_CustomerApplySaveData(obj)
					.then((res) => {
						if (res.Success) {
							this.$sucessToast("已备案");
							setTimeout(function() {
								that.loading = false
								uni.navigateBack()
								uni.hideLoading()
							}, 2500)
						} else {
							that.loading = false
							this.$errorToast(res.Msg);
						}
					});
			},


			init() {
				(this.data = []), (this.entity = {});
			},

			openForm(row) {
				this.init();
				this.row = row;
				// console.log(row);
				if (row) {
					this.Id = row.Id;
					this.getDataList();
				}
			},
		},
	};
</script>

<style lang="less" scoped>
	/* 设置 label 的样式 */
	::v-deep.uni-forms-item {
		padding-right: 40rpx !important;

		/* 例如，设置 label 的宽度和对齐方式 */
		.uni-forms-item__label {
			display: flex !important;
			justify-content: flex-end !important;
		}
	}

	.submitButton {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 65px;
		/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
		height: calc(65px + constant(safe-area-inset-bottom));
		/* 直接扩展高度，因为padding-bottom是内边距 */
		height: calc(65px + env(safe-area-inset-bottom));
		/* 直接扩展高度 */
		background: #fff;
		padding-top: 10px;
		box-sizing: border-box;
		padding-bottom: constant(safe-area-inset-bottom);
		/*兼容 iOS<11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容iOS>= 11.2*/
		border-top: 1px solid #e9e9e9;
		padding-left: 15px;
		padding-right: 15px;
	}
</style>